//
//  TJMineController.m
//  CrossBorderPayment
//
//  Created by hc-101 on 2020/6/9.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJMineController.h"
#import "TJLanguageSettingController.h"
#import "TJShareController.h"
@interface TJMineController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) NSArray *datas;
/**头像 */
@property (weak, nonatomic) UIImageView *portraitImageView;
@property (copy, nonatomic) NSString *filePath;
@property (weak, nonatomic) UILabel *textLabel;

@end

@implementation TJMineController


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setUpUserData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.hidden = YES;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 150 + StatusBarHeight - 20)];
    UIImageView *portraitImageView = [UIImageView tj_addToView:headerView];
    [portraitImageView shearRoundedCornersWithRadiu:30];
    portraitImageView.backgroundColor = UIColor_Hex(0xf2f2f2);
    //获取本地的头像
    portraitImageView.image = [Tools avatarImage];
    [portraitImageView addTapGesturesWithTarget:self action:@selector(tapPortraitImageView)];
    [portraitImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.width.height.offset(60);
        make.centerY.offset((StatusBarHeight - 20) * 0.5 + 10);
    }];
    /**Hi + 昵称*/
    UILabel *textLabel = [UILabel lableWithSuperView:headerView font:MediumFont(20) color:UIColor_Hex(0x333333) title:[NSString stringWithFormat:@"Hi"] textAlignment:NSTextAlignmentLeft];
    [textLabel addTapGesturesWithTarget:self action:@selector(tapTextLabel)];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(portraitImageView);
        make.width.mas_greaterThanOrEqualTo(100);
        make.left.equalTo(portraitImageView.mas_right).offset(20);
    }];
    
    UILabel *subTextLabel = [UILabel lableWithSuperView:headerView font:UIFont_Px(14) color:UIColor_Hex(0x999999) title:[NSString stringWithFormat:@"%@ %@ UID: %@", @"欢迎来到".localizedString, [Tools appName], TJUserInfo.readInfo.uuid] textAlignment:NSTextAlignmentLeft];
    [subTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(portraitImageView);
        make.left.equalTo(textLabel);
    }];
    
    UILabel *portraitTipLabel = [UILabel lableWithSuperView:headerView font:UIFont_Px(11) color:UIColor_Hex(0x999999) title:@"更换头像".localizedString textAlignment:NSTextAlignmentLeft];
    [portraitTipLabel addTapGesturesWithTarget:self action:@selector(tapPortraitImageView)];
    [portraitTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(portraitImageView.mas_bottom);
        make.centerX.equalTo(portraitImageView);
    }];
    
    _textLabel = textLabel;
    
    self.textLabel.text = [NSString stringWithFormat:@"%@,%@",@"Hi", TJUserInfo.readInfo.nickName ?: @""];
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableView.backgroundColor = UIColor.whiteColor;
    
    self.tableView.tableHeaderView = headerView;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = 60;
    [self.tableView registerClass:TJStyle1Cell.self forCellReuseIdentifier:style1Cell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    }];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 164)];
    self.tableView.tableFooterView = footerView;
    UIButton *exitButon = [UIButton buttonWithSuperView:footerView font:UIFont_Px(16) color:UIColor.whiteColor title:@"退出".localizedString];
    [exitButon shearRoundedCornersWithRadiu:3];
    exitButon.backgroundColor = UIColor.tj_mainColor;
    [exitButon addTarget:self action:@selector(didClickExitButton) forControlEvents:UIControlEventTouchUpInside];
    [exitButon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
        make.left.offset(16);
        make.right.offset(-16);
        make.height.offset(44);
    }];
    /**语言设置btn */
    UIButton *languageButton = [UIButton tj_addToView:self.view];
    [languageButton setImage:[UIImage imageNamed:@"languageIcon"] forState:UIControlStateNormal];
    [languageButton setImage:[UIImage imageNamed:@"languageIcon"] forState:UIControlStateHighlighted];
    [languageButton addTarget:self action:@selector(didClickLanguageButton) forControlEvents:UIControlEventTouchUpInside];
    [languageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.width.offset(68);
        make.height.offset(62);
        make.bottom.offset(-36);
    }];
    
    _portraitImageView = portraitImageView;
    
}

/**改换昵称 */
- (void)tapTextLabel {
    [self.navigationController pushViewControllerWithName:@"TJModifyNicknameController" title:nil animated:YES];
}
- (void)didClickLanguageButton {
    [self presentViewController:[[TJLanguageSettingController alloc] init] animated:YES completion:nil];
}
/**退出登录 */
- (void)didClickExitButton {
    
    TJUIAlertController *alertController = [TJUIAlertController alertControllerWithTitle:@"提示".localizedString message:@"是否退出登录?".localizedString preferredStyle:QMUIAlertControllerStyleAlert];
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"退出".localizedString style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        self.tabBarController.selectedIndex = 0;
        [[NSNotificationCenter defaultCenter] postNotificationName:tokenErrorNotification object:nil];
    }]];
    
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"取消".localizedString style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
    }]];
    alertController.alertDestructiveButtonAttributes = @{NSForegroundColorAttributeName:UIColor_Hex(0x9EA0A4),NSFontAttributeName:UIFontMake(16), NSKernAttributeName:@(0)};
    alertController.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:UIColorRed,NSFontAttributeName:UIFontMake(16),NSKernAttributeName:@(0)};
    [alertController showWithAnimated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJStyle1Cell *cell = [tableView dequeueReusableCellWithIdentifier:style1Cell forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TJCellStyleModel *model = self.datas[indexPath.row];
    
    if ([model.identification isEqualToString:@"payWay"]) {//支付方式
        
        TJUserInfo *userInfo = TJUserInfo.readInfo;
        
        if (![userInfo.cardState isEqualToString:@"PASS"]) {
            [TJHud showAutoHideMessage:@"请先身份认证".localizedString];
            return;
        }
        
        if (userInfo.payAliay.replacingEmptyString.length || userInfo.payWechat.replacingEmptyString.length || userInfo.bankCard.replacingEmptyString.length) {//支付方式列表
            [self.navigationController pushViewControllerWithName:@"TJPayWayListController" title:nil animated:YES];
        } else {
            //添加支付方式
            [self.navigationController pushViewControllerWithName:@"TJPayWayController" title:model.text animated:YES];
        }
        
        return;
    }
    if ([model.identification isEqualToString:@"orderRecord"]) {//订单记录 TJOrderRecardListController
        [self.navigationController pushViewControllerWithName:@"TJOrderRecardListController" title:model.text animated:YES];
        return;
    }
    
    if ([model.identification isEqualToString:@"security"]) {//安全中心
        [self.navigationController pushViewControllerWithName:@"TJSecurityCenterController" title:model.text animated:YES];
        return;
    }
    
    /**身份认证 审核状态  WAIT 等待 PASS 通过 NO为null则没有申请 */
    if ([model.identification isEqualToString:@"authentication"]) {
        if ([TJUserInfo.readInfo.cardState isEqualToString:@"NO"]) {
            [self.navigationController pushViewControllerWithName:@"TJIdentityAuthControlller" title:model.text animated:YES];
            return;
        }
        
        if ([TJUserInfo.readInfo.cardState isEqualToString:@"WAIT"]) {
            [self alertWithTitle:@"认证中...".localizedString message:nil leftButtonName:@"确定".localizedString rightButtonName:nil leftButtonBlock:nil rightButtonBlock:nil];
            return;
        }
        if ([TJUserInfo.readInfo.cardState isEqualToString:@"PASS"]) {
            [self alertWithTitle:@"已认证".localizedString message:nil leftButtonName:@"确定".localizedString rightButtonName:nil leftButtonBlock:nil rightButtonBlock:nil];
            return;
        }
        
    }
    
    if ([model.identification isEqualToString:@"share"]) {//分享
        TJShareController *shareVC = [TJShareController new];
        [self.navigationController presentViewController:shareVC animated:NO completion:nil];
    }
}

- (void)setUpUserData{
    TJUserInfo *userInfo = TJUserInfo.readInfo;
    if (userInfo.headLink.replacingEmptyString.length) {
        [self.portraitImageView sd_setImageWithURL:[NSURL URLWithString:userInfo.headLink]];
    }
    
    
    //获取用户信息
    [TJNetworking.shareNetworking updateUserInfoAndLoading:NO success:^(TJUserInfo * _Nonnull userInfo) {
        self.textLabel.text = [NSString stringWithFormat:@"%@,%@",@"Hi", userInfo.nickName ?: @""];
    }];
    
    
    
}
- (void)tapPortraitImageView {
    
    TJUIAlertController *alert = [[TJUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"取消".localizedString style:QMUIAlertActionStyleCancel handler:nil]];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"相册".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES ;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }]];
    
    [alert addAction:[QMUIAlertAction actionWithTitle:@"拍照".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            
            [self alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromCamera];
        
    }]];
    [alert showWithAnimated:YES];
    
}


#pragma mark - 拍照
- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        TJLog(@"不支持拍照功能");
    }
}


//UIimagePickerCotrollerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *newImage = info[UIImagePickerControllerEditedImage];
    [self uploadImage:newImage];
}

#pragma mark ——— 图片上传
- (void)uploadImage:(UIImage *)image {
    
    
    [self showloading];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        
        NSLog(@"dispatch_semaphore_t");
        
        [TJNetworking.shareNetworking updataImageWithImage:image success:^(NSDictionary * resp, id data) {
            
            self.filePath = data;
            
            dispatch_semaphore_signal(semaphore);
            
        } failure:^(NSError *errpr) {
            [self hiddenloading];
            [TJHud showAutoHideMessage:@"上传失败, 请稍后再试".localizedString];
        }];
        
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        [TJNetworking.shareNetworking POSTNew:@"member/member/setHeadLink" parameters:@{@"headUrl": self.filePath ?: @"", @"userId": TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [image asynImageSize:HeadPortraitSize color:[UIColor whiteColor] finishiBlock:^(UIImage *newImage) {
                    self.portraitImageView.image = newImage;
                    [Tools saveAvatarImageWithImage:newImage];
                }];
            });
            
            [self hiddenloading];
        } failure:^(NSError * _Nonnull error) {
            [self hiddenloading];
            [TJHud showAutoHideMessage:@"上传失败, 请稍后再试".localizedString];
        }];
        
    });
    
    
}


//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (NSArray *)datas {
    if (!_datas) {
        NSArray *arr = @[
            @{
                @"icon": @"authenticationIcon",
                @"text": @"身份认证".localizedString,
                @"detailText": @"",
                @"identification": @"authentication",
                @"hasArrow": @(1),
            },
            @{
                @"icon": @"addressManagerIcon",
                @"text": @"订单记录".localizedString,
                @"detailText": @"",
                @"identification": @"orderRecord",
                @"hasArrow": @(1),
            },
            @{
                @"icon": @"securityIcon",
                @"text": @"安全中心".localizedString,
                @"detailText": @"",
                @"identification": @"security",
                @"hasArrow": @(1),
            },
            @{
                @"icon": @"collectionIcon",
                @"text": @"支付方式".localizedString,
                @"detailText": @"",
                @"identification": @"payWay",
                @"hasArrow": @(1),
            },
            @{
                @"icon": @"user_icon",
                @"text": @"分享有礼".localizedString,
                @"detailText": @"",
                @"identification": @"share",
                @"hasArrow": @(1),
            }
        ];
        
        _datas = [TJCellStyleModel mj_objectArrayWithKeyValuesArray:arr];
    }
    return _datas;
    
}

@end
